package _case

import (
	"io"
	"log"
	"os"
	"path"
)

// 边读边写文件
func OneSideReadWriteToDest() {
	list := GetFile(sourceDir)
	for _, f := range list {
		_, name := path.Split(f)
		destName := destDir + "one-side/" + name
		oneSideReadWrite(f, destName)
	}
}

func oneSideReadWrite(src string, dest string) {
	s, err := os.Open(src)
	if err != nil {
		log.Fatal(err)
	}
	defer s.Close()

	dst, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Fatal(err)
	}
	defer dst.Close()

	buf := make([]byte, 1024)
	for {
		n, err := s.Read(buf)
		if err != nil && err != io.EOF {
			log.Fatal(err)
		}

		if n == 0 {
			break
		}

		_, err = dst.Write(buf[:n])
		if err != nil {
			log.Fatal(err)
		}
	}
}
